package com.android.bookgarden.utli;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;


import com.android.bookgarden.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class DownLoadApp extends Thread {

    /* 下载包安装路径 */
    private static final String savePath = System.getenv("EXTERNAL_STORAGE")+"/lingjsy/";
    private static final String saveFileName = savePath ;
    private boolean interceptFlag = false;
    private String apkUrl = "";
    private Handler handler;
    private Context context;
    private String apkFile;


    public DownLoadApp(String apkUrl, Handler handler, Context context) {
        this.apkUrl = apkUrl;
        this.handler = handler;
        this.context = context;
    }


    private Dialog downloadDialog;
    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;
    private int progress = 0;
    private static final int DOWN_UPDATE = 1;

    private static final int DOWN_OVER = 2;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:
                    mProgress.setProgress(progress);
                    break;
                case DOWN_OVER:
//                    AppUtils.installApk(context,apkFile);

                    Intent  intent = FileOpenHelper.openFile(apkFile);
                    context.startActivity(intent);
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public void showDownLoadProgress() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("下载中，请稍后......");

        final LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.progress);

        builder.setView(v);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;

            }
        });
        downloadDialog = builder.create();
        downloadDialog.show();
        downloadDialog.setCanceledOnTouchOutside(false);
    }

    public DownLoadApp(Context context) {
        this.context = context;
    }

    @Override
    public void run() {
        try {
            URL url = new URL(apkUrl);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try {
                conn.connect();
            } catch (RuntimeException e) {

            }
            int length = conn.getContentLength();
            InputStream is = conn.getInputStream();

            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdir();
            } else {
                file.delete();
                file.mkdir();
            }
            String filetype = "linjia.apk";

             apkFile = saveFileName+filetype;
            File ApkFile = new File(apkFile);
            FileOutputStream fos = new FileOutputStream(ApkFile);

            int count = 0;
            byte buf[] = new byte[1024];

            do {
                int numread = is.read(buf);
                count += numread;
                progress = (int) (((float) count / length) * 100);
                //更新进度
                mHandler.sendEmptyMessage(DOWN_UPDATE);
                if (numread <= 0) {
                    //下载完成通知安装
                    mHandler.sendEmptyMessage(DOWN_OVER);
                    downloadDialog.dismiss();
                    break;
                }
                fos.write(buf, 0, numread);
            } while (!interceptFlag);//点击取消就停止下载.

            fos.close();
            is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file://"+ apkFile),"application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}





